<template>
  <bottomChartContent title="质量指标分析">
    <div id="qualityContainer"></div>
  </bottomChartContent>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import bottomChartContent from "../baseComponent/bottomChartContent.vue";
import * as echarts from "echarts";
import { qualityData } from "@/request/product";

let qualityChart = null;
const axisStyle = {
  axisLabel: {
    color: "#fff",
    fontSize: 24,
    interval: 1,
  },
};
const seriesBarOption = {
  type: "bar",
  stack: "total",
};

const createLine = (goodData, monthData, badData, barDom) => {
  qualityChart = echarts.init(barDom);
  let options = {
    color: ["#2499F8", "#FE9901"],
    tooltip: {
    //   trigger: "axis",
      formatter(data) {
        let arrData = data.seriesName === '好' ? goodData : badData 
        return `<div>${data.name}:</div>
        <div style="width: 120px;display:flex;justify-content: space-between"><span>${data.seriesName}</span>    <span>${arrData[data.dataIndex].value}</span></div>`;
      },
      textStyle: {
        fontSize: 26,
      },
    },
    grid: {
      left: "10%",
      bottom: "30%",
      top: "10%",
    },
    xAxis: {
      ...axisStyle,
      type: "category",
      data: monthData,
    },
    yAxis: {
      axisLabel: {
        color: "#fff",
        fontSize: 24,
        formatter: (val) => {
          return 1000 * val;
        },
      },
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        ...seriesBarOption,
        name: "好",
        data: goodData.map((item) => item.ratio),
        label: {
          show: true,
          color: "#fff",
          fontSize: 24,
          formatter: (value) => {
            return goodData[value.dataIndex].value;
          },
        },
      },
      {
        ...seriesBarOption,
        name: "坏",
        data: badData.map((item) => item.ratio),
        label: {
          show: true,
          color: "red",
          fontSize: 24,
          formatter: (value) => {
            return badData[value.dataIndex].value;
          },
        },
      },
    ],
  };
  qualityChart.setOption(options);
};
onMounted(async () => {
  let {
    data: { data: qualityDataRes },
  } = await qualityData();
  let goodData = [],
    monthData = [],
    badData = [];
  qualityDataRes.map((item) => {
    let total = item.good + item.bad;
    goodData.push({ ratio: item.good / total, value: item.good });
    monthData.push(item.month);
    badData.push({ ratio: item.bad / total, value: item.bad });
  });
  createLine(
    goodData,
    monthData,
    badData,
    document.getElementById("qualityContainer")
  );
});
onUnmounted(() => {
  echarts.dispose(qualityChart);
  qualityChart = null;
});
</script>

<style lang="less" scoped>
#qualityContainer {
  width: 100%;
  height: 100%;
}
</style>
